Booleans in JavaScript represent one of two values: true
or false
. They are often used
in conditional testing.
Boolean values can be created directly or as the result of comparisons:
let isTrue = true;
let isFalse = false;
let comparison = 10 > 5; // true
let equality = 10 === 10; // false (compairs value and data type)
let equal = 10 == "10"; // true (compairs value)
let inequality = 10 !== 5; // true
Booleans can also be created using the Boolean
object:
let boolObject = new Boolean(true);
console.log(boolObject); // Outputs: [Boolean: true]
The Boolean
object has a few methods:
let bool = true;
console.log(bool.toString()); // Outputs: "true"
console.log(bool.valueOf()); // Outputs: true
Values can be converted to booleans using the Boolean()
function:
console.log(Boolean(0)); // Outputs: false
console.log(Boolean(1)); // Outputs: true
console.log(Boolean("")); // Outputs: false
console.log(Boolean("Hello")); // Outputs: true
console.log(Boolean(null)); // Outputs: false
console.log(Boolean(undefined)); // Outputs: false
JavaScript provides several logical operators to work with booleans:
true
if both operands are true.true
if at least one operand is true.let a = true;
let b = false;
console.log(a && b); // Outputs: false
console.log(a || b); // Outputs: true
console.log(!a); // Outputs: false
Booleans are often used in conditional statements to control the flow of the program:
let isRaining = true;
if (isRaining) {
console.log("Take an umbrella!");
} else {
console.log("No need for an umbrella.");
}